import React from 'react';
import {connect} from 'react-redux';
import {Card, Pagination, Tabs, Badge, Divider, Row, Col, Icon, Popover} from 'antd';
const TabPane = Tabs.TabPane;
import {messages} from 'share/common'
import messagesService from 'containers/messages-center/messages-center.service'
import "styles/messages-center/message-center.scss"
import moment from "moment";
import menuRoute from "routes/menuRoute";
import SearchArea from 'components/search-area'

class MessagesCenter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      activeKey: "",
      channelCode: "",
      messagesList: [],
      infoList: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        current: 1,
      },
      id: null,//系统消息channelId
      messagesCenterDetail: menuRoute.getRouteItem('messages-center-detail', 'key').url,
      unreadList: [],
      searchForm: [
        {
          type: 'list',
          id: 'body',
          label: messages('messages-center.key4')/*申请人姓名*/,
          listType: 'user',
          labelKey: 'fullName',
          valueKey: 'id',
        },
        {type: 'input', id: 'keyword', label: messages('common.document.code')/*单号*/,},
        {
          type: 'rangePicker', id: 'dateRange',
          label: messages('financial-management.key479')/*提交日期*/
        },
      ],
      searchParams: {body: [], keyword: "", submitDateFrom: "", submitDateTo: ""},
      search: false,//是否处于搜索状态
    };
  }

  componentWillMount() {
    this.getMessagesCenterNameList();
  }

  //获取左侧消息中心tab列表
  getMessagesCenterNameList = () => {
    messagesService.getMessagesCenterNameList().then(res => {
      if(res && res.data) {
        this.setState({
          messagesList: res.data,
          id: res.data[0].id,
          activeKey: res.data[0].id,
          channelCode: res.data[0].channelCode,
        }, () => {
          if (this.state.channelCode === 'NORMAL_NOTIFICATION') {
            this.searchMessage();
          } else {
            this.getMessagesCenterList();
          }
          this.alreadyRead();
          this.getMessagesListLatest();
        })
      }
    }).catch(err => {

    })
  };

  //获取小红点
  getMessagesListLatest = () => {
    let arr = [];
    messagesService.getMessagesListLatest().then(res => {
      res.data.map(item => {
        if(item.unreadMessageCount > 0){
          arr.addIfNotExist(item.id)
        }
      });
      this.setState({
        unreadList: arr,
      })
    }).catch(err => {

    })
  };

  //获取右侧消息列表
  getMessagesCenterList = () => {
    const {activeKey,page,pageSize} = this.state;
    messagesService.getMessagesCenterList(activeKey, page, pageSize).then(res => {
      this.setState({
        infoList: res.data.records,
        pagination: {
          total: res.data.total || 0,
          current: this.state.page + 1,
        }
      })
    }).catch(err => {

    })
  };

  //点击分页
  onPageChange = (page) => {
    const {channelCode, searchParams} = this.state;
    if(page - 1 !== this.state.page){
      this.setState({
        page: page - 1
      }, () => {
        if(channelCode === 'NORMAL_NOTIFICATION'){
          this.searchMessage(searchParams, this.state.page);
        }else{
          this.getMessagesCenterList();
        }
      });
    }
  };

  onTabChange = (activeKey) => {
    const {messagesList} = this.state;
    messagesList.map(item => {
      if(item.id === activeKey){
        this.setState({
          channelCode: item.channelCode,
        });
      }
    });
    this.setState({
      page: 0,
      activeKey,
    }, () => {
      let arr = messagesList.filter(item => (item.id === activeKey) && (item.channelCode === "NORMAL_NOTIFICATION"));
      if(arr && arr.length){
        this.searchMessage();
      }else{
        this.getMessagesCenterList();
      }
      this.alreadyRead();
      this.getMessagesListLatest();
    })
  };

  //消息已读
  alreadyRead = () => {
    const {channelCode} = this.state;
    messagesService.alreadyRead(channelCode).then(res => {
    }).catch(err => {

    })
  };

  goToDetail = (e, id) => {
    const {messagesCenterDetail} = this.state;
    this.context.router.push(messagesCenterDetail.replace(":id", id))
  };

  jumpUrl = (url) => {
    window.localStorage.setItem('mail_approve', url ? url : window.location.href);
    window.location.href = url;
  };

  //查询消息
  searchMessage = (values, searchPage) => {
    const {page} = this.state;
    if(values && values.dateRange && values.dateRange.length > 0) {
      values.submitDateFrom = values.dateRange[0].utc().format('YYYY-MM-DD');
      values.submitDateTo = values.dateRange[1].utc().format('YYYY-MM-DD');
    }
    this.setState({
      page: searchPage || 0,
      search: true,
      searchParams: values,
    }, () => {
      let item = {
        page: this.state.page,
        size: 10,
        channelCode: "NORMAL_NOTIFICATION",
        client: "web",
        submitDateFrom: values && values.submitDateFrom ? values.submitDateFrom : "",
        submitDateTo: values && values.submitDateTo ? values.submitDateTo : "",
      };
      let params = Object.assign(values || {}, item);
      messagesService.searchMessage(params).then(res => {
        this.setState({
          infoList: res.data.records,
          pagination: {
            total: res.data.total || 0,
            current: this.state.page + 1,
          }
        })
      }).catch(err => {

      })
    });
  };

  clear = () => {
    this.setState({
      search: false,
      page: 0,
      searchParams: {},
    }, () => {
      this.searchMessage()
    })
  };

  render() {
    const {messagesList, activeKey, channelCode, infoList, pagination, unreadList, searchForm} = this.state;
    return (
      <div className={"message-center"}>
        <div className={"message-center-content-wrap"}>
          <div className={"message-center-left"}>
            {
              messagesList.length ?
                <Tabs tabPosition={'left'} style={{fontSize: 18}} activeKey={activeKey} onChange={this.onTabChange}>
                  {
                    messagesList.map((item) => {
                      return (
                        <TabPane key={item.id}
                                 tab={
                                   <div style={{width: 190, textAlign: "left"}}>
                                     <span style={{width: 170, float: "left", textOverflow: "ellipsis", overflow: "hidden"}}>
                                       <Popover content={item.channelName}>
                                        <img src={item.channelIcon} style={{width: 20, height: 20,marginRight: 10}}/>
                                        {item.channelName}
                                       </Popover>
                                     </span>
                                     <span style={{float: "right"}}>
                                       {unreadList.indexOf(item.id) === -1 ? "" : <Badge status="error" />}
                                     </span>
                                     <div className="clear"/>
                                   </div>}>
                        </TabPane>
                      )
                    })
                  }
                </Tabs>
                :
                <div>{messages('messages-center.key1')/*当前暂无消息*/}</div>
            }
          </div>
            {infoList.length ?
              <div className={"message-center-right"}>
                {
                  channelCode === 'NORMAL_NOTIFICATION' &&
                  <div style={{marginBottom: 24}}>
                    <SearchArea
                      searchForm={searchForm}
                      submitHandle={(values) => this.searchMessage(values, 0)}
                      clearHandle={this.clear}/>
                  </div>
                }
                {
                  infoList.map(item => {
                    return(
                      channelCode === "SYSTEM_NOTIFICATION" ?
                      <Card key={item.id}
                            bordered={true}
                            hoverable={true}
                            style={{ width: 720, marginBottom: 24}}
                            bodyStyle={{padding: "16px 24px"}} onClick={(e) => {this.goToDetail(e, item.id)}}>
                        <div className={"message-center-title"}>
                          <h3>{item.title}</h3>
                        </div>
                        <div style={{float: 'right'}}>
                          {moment(item.createdDate).format('YYYY-MM-DD  HH:mm')}
                        </div>
                        <div className={"message-center-content"} style={item.imageLink ? {width: 380, height: 160} : {}}>
                          <div dangerouslySetInnerHTML={{__html: item.content}}/>
                        </div>
                        {
                          item.imageLink ?
                            <div className={"message-center-img"}>
                              <img src={item.imageLink} style={{width: 250, height: 150}}/>
                            </div>
                            : null
                        }
                      </Card>
                          :
                          (
                            channelCode === "NORMAL_NOTIFICATION" || channelCode === "DOCUMENT_NOTIFICATION" ?
                            <div  key={item.id} onClick={()=>{this.jumpUrl(item.webLink)}}>
                              <Card key={item.id}
                                    bordered={true}
                                    hoverable={true}
                                    style={{ width: 720, marginBottom: 24}}
                                    bodyStyle={{padding: "16px 24px"}}>
                                <div className={"message-center-title"}>
                                  <h3>{item.title}</h3>
                                  <h4>{item.subtitle}</h4>
                                </div>
                                <div style={{float: 'right', fontSize: 12}}>
                                  {moment(item.createdDate).format('YYYY-MM-DD  HH:mm')}
                                </div>
                                <Row style={{color: "#999999", fontSize: 12}}>
                                  <Col span={8}>
                                    {messages('common.amount')/*金额*/}：{item.amount ? `${item.amount.toFixed(2)} ${item.currencyCode}` : '-'}
                                  </Col>
                                  <Col span={8}>{messages('common.submit.date')/*提交日期*/}：{moment(item.submitDate).format('YYYY-MM-DD')}</Col>
                                  <Col span={8}>{messages('common.document.code')/*单号*/}：{item.businessCode}</Col>
                                </Row>
                                {
                                  ( item.reason || item.remark ) &&
                                  <Row style={{color: "#999999", fontSize: 12}}>
                                    <Col span={24}>{messages('messages-center.key3')/*事由/备注*/}：{item.reason}&nbsp;&nbsp;{item.remark}</Col>
                                  </Row>
                                }
                                {
                                  item.description &&
                                  <Divider dashed={true}/>
                                }
                                {
                                  item.status === "R" ?
                                    item.description &&
                                  <div style={{color: "red"}}><Icon type="message" />&nbsp;&nbsp;{item.description}</div>
                                    :
                                    item.description &&
                                    <div style={{color: "#999999"}}>
                                      <Icon type="message" style={{color: "#3784cd"}}/>&nbsp;&nbsp;{item.description}
                                    </div>
                                }
                              </Card>
                            </div>
                              :
                              <div></div>
                          )
                    )
                  })
                }
                <div className={"message-center-pagination"}>
                  <div style={{float: "right"}}>
                    <Pagination showQuickJumper
                                size={'small'}
                                total={pagination.total}
                                current={pagination.current}
                                onChange={this.onPageChange}/>
                  </div>
                </div>
              </div>
              :
              (
                messagesList.length ?
                  <div style={{marginTop: 6, fontSize: 15}} className={"message-center-right"}>
                    {
                      channelCode === 'NORMAL_NOTIFICATION' &&
                      <div style={{marginBottom: 24}}>
                        <SearchArea
                          searchForm={searchForm}
                          submitHandle={this.searchMessage}
                          clearHandle={this.clear}/>
                      </div>
                    }
                    {messages('messages-center.key1')/*当前暂无消息*/}
                  </div>
                  :
                  null
              )
            }
            <div className={"clear"}/>
        </div>
      </div>
    )
  }

}

MessagesCenter.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(MessagesCenter);
